#include "OwnRadar.h"
#include "../../Target/data_interface.h"
#include "../radar_data_manager.h"

#define RADARDATAHEADER (0X55AAAA55)
#define OWN_ONE_FRAME_DATA (1024)
#define OWNRADAR_LOG_TITLE ("$OWN")
#define RANGE_RATIO (1.2)

OwnRadar::OwnRadar(boost::asio::io_service& io_service)
    :Radar(io_service), m_old_range(-1), m_single_data("")
{
    m_radar_type = UDP_RADAR;
    set_log_title(OWNRADAR_LOG_TITLE);
}

OwnRadar::~OwnRadar()
{
    m_is_radar_running = false;

    m_count_down.wait();
}

bool OwnRadar::do_video_processer(const char *data, unsigned int length)
{
    if (length != sizeof(OwnItemData))
    {
        return false;
    }

    OwnItemData *spoke = (OwnItemData*)data;

    if (spoke->header != RADARDATAHEADER)
    {
        return false;
    }

    OnRadarRangeChanged(spoke->range);

    sln_radar_data_manager::instance().UpdateDataSpoke(spoke->bearing, spoke->data, 32768);

    convertData(spoke->data, OWN_ONE_FRAME_DATA);

    SetRadarRangeMeters(RANGE_RATIO * spoke->range);

    onRadarDataSpoke(spoke->bearing, (uint8_t*)m_single_data.c_str(), OWN_ONE_FRAME_DATA);

    return true;
}

void OwnRadar::do_status_processer(const char *data, unsigned int length, unsigned int radar_key)
{
    if (length != sizeof(OwnStatusData))
    {
        return;
    }

    OwnStatusData *o_data = (OwnStatusData *)data;

    if (o_data->header != STATUS_HEADER)
    {
        return;
    }

    m_radar_status.secs_per_cycle.is_valid = true;

    m_radar_status.secs_per_cycle.value = o_data->arp*0.008 * pow(10.0, -6);
}

void OwnRadar::convertData(short *data, unsigned int length)
{
    m_single_data = "";

    for (int i = 0; i < length; ++i)
    {
        unsigned char val = 0;

        val = fabs(data[i]) / 32767 * 255.0;

        if (val > 127)
        {
            val = 255;
        }
        else
        {
            val *= 2;
        }

        m_single_data.append(1, (char)val);
    }
}

void OwnRadar::OnRadarRangeChanged(unsigned int range)
{
    if (m_old_range == range)
    {
        m_is_radar_range_changed = false;
    }
    else
    {
        m_old_range = range;
        m_is_radar_range_changed = true;
    }
}

void OwnRadar::StartOwnProcess()
{
}
